import * as joi from 'joi'
import { parameter, get, post, del, controller, definition, summary, response, tag, ENUM_PARAM_IN } from 'koa-joi-swagger-ts'
import kjsRouter from '../util/swagger'
import Router from '@koa/router'

@definition('User', 'User Entity')
class UserSchema {
  userName = joi.string().min(6).description('username').required()
  userPass = joi.string().min(6).description('password').required()
}

@controller('/v3/user-svr')
class BaseController {
  @get('/')
  index() {
    return false
  }
}

const controllerFun = async (controller: (ctx: Router.RouterContext) => void, ctx: Router.RouterContext, next: () => void, summary: string): Promise<void> => {
  console.log(`${ctx.request.method} ${ctx.request.url}`)
  try {
    await controller(ctx)
    next()
  } catch (e) {
    console.log(e, `Error while executing '${summary}'`)
  }
}

@controller('/user')
class UserController extends BaseController {
  @tag('示例')
  @summary('查询用户id')
  @get('/')
  @parameter('userId', joi.string().required(), ENUM_PARAM_IN.query)
  doGet(ctx: Router.RouterContext) {
    ctx.body = Date.now()
  }

  @tag('示例')
  @summary('rest风格-查询用户id')
  @get('/{userId}')
  @parameter('userId', joi.number().min(2).description('userId'), ENUM_PARAM_IN.path)
  @response(200, { $ref: UserSchema })
  getUser(ctx: Router.RouterContext) {
    ctx.body = { userName: ctx.params.userId.toString(), userPass: Date.now().toString() }
  }

  @tag('示例')
  @post('/upload')
  @parameter('file1', { type: 'file' }, ENUM_PARAM_IN.formData)
  doUpload(ctx: Router.RouterContext) {
    console.log('doUpload', ctx.request.files)
    ctx.body = { fileObj: ctx.request.files }
  }

  @tag('示例')
  @del('/remove')
  @parameter('userId', { type: 'string' }, ENUM_PARAM_IN.query)
  delUser(ctx: Router.RouterContext) {
    console.log('delUser', ctx)
    ctx.body = 'success'
  }
}

kjsRouter.loadDefinition(UserSchema)
kjsRouter.loadController(UserController, controllerFun)

export default kjsRouter